package com.kyzh.core.activities

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.webkit.*
import com.bytedance.applog.game.GameReportHelper
import com.google.gson.Gson
import com.gushenge.atools.util.AView
import com.gushenge.core.base.Base.BASEURL
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.PayJuBean
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.requests.AppRequest
import com.gushenge.core.requests.GameRequest
import com.gushenge.core.toast
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.callback.SelectCallback
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.kyzh.core.R
import com.kyzh.core.dialog.showExitQunDialog
import com.kyzh.core.dialog.showLoadingDialog
import com.kyzh.core.pager.home.MainActivity
import com.kyzh.core.pager.weal.community.CommunityActivity
import com.kyzh.core.pager.weal.coupon.ZJLSActivity
import com.kyzh.core.pager.weal.groupchat.GroupChatActivity
import com.kyzh.core.utils.*
import kotlinx.android.synthetic.main.act_browser.*
import kotlinx.android.synthetic.main.act_browser.close
import kotlinx.android.synthetic.main.act_browser.tvTitle
import kotlinx.android.synthetic.main.activity_game_detail2.*
import org.jetbrains.anko.browse
import org.jetbrains.anko.intentFor
import java.util.*

class BrowserActivity : BaseActivity() {

    private var link: String? = null
    private var name: String? = null
    private var type: Int = 0

    private var mUploadCallbackAboveL //回调图片选择，5.0以上
            : ValueCallback<Array<Uri?>?>? = null
    private var canClose = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_browser)
//        AView.setMargins(toolbar, 0, AView.getStatusBarHeight(this), 0, 0)
        initData()
        initView()
    }

    private fun initData() {
        val intent = intent
        link = intent.getStringExtra(GlobalKeys.LINK)
        name = intent.getStringExtra(GlobalKeys.TITLE)
        type = intent.getIntExtra("TYPE", 0)
        tvTitle.text = name ?: ""
        back.setOnClickListener {
            if (webview.canGoBack()) {
                webview.goBack()
            } else {
                finish()
            }
        }
        refresh.setOnClickListener {
            webview.loadUrl(link)
        }
        close.setOnClickListener {
            finish()
        }
        canClose = intent.getBooleanExtra(GlobalKeys.KEY, false)
    }

    inner class JsObject {
        @JavascriptInterface
        fun h5pay(msg: String) {
            kotlin.runCatching {
                val fromJson = Gson().fromJson(msg, PayJuBean::class.java)
                //商品类型，商品名称，商品ID    ，商品数量，支付渠道，币种，是否成功（必传），金额（必传）
                GameReportHelper.onEventPurchase(
                    "coin",
                    "ptb",
                    "",
                    1,
                    "b",
                    "¥",
                    true,
                    fromJson.money
                );
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initView() {
        val webSettings = webview.settings
        webSettings.allowFileAccess = true// 设置允许访问文件数据
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true
        webSettings.allowFileAccessFromFileURLs = true
        WebStorage.getInstance().deleteAllData()
        webview.addJavascriptInterface(JsObject(), "android")

        // 关键性代码，这里要给webview添加这行代码，才可以点击之后正常播放音频。记录一下。
        webSettings.mediaPlaybackRequiresUserGesture = false
        webSettings.setAppCacheEnabled(false)

        //设置WebView属性，能够执行Javascript脚本
        webSettings.javaScriptEnabled = true
        webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                if (name.isNullOrEmpty()) {
                    tvTitle.setText(title ?: "")
                } else {
                    if (name != getString(R.string.privacyPolicy) && name != getString(R.string.registerAgreement)) {
                        tvTitle.setText(title ?: "")
                    }
                }

            }

            override fun onShowFileChooser(
                webView: WebView?,
                filePathCallback: ValueCallback<Array<Uri?>?>,
                fileChooserParams: FileChooserParams?
            ): Boolean {
                mUploadCallbackAboveL = filePathCallback
                openImageChooserActivity()
                return true
            }

            override fun onJsAlert(
                view: WebView?,
                url: String?,
                message: String?,
                result: JsResult?
            ): Boolean = jsAlert(view, url, message, result)

        }
        webview.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                handler?.proceed()
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                try {
                    Log.e("TAG", "shouldOverrideUrlLoading: " + url)
                    if (url.startsWith("http") || url.startsWith("https")) {
                        //处理http和https开头的url
                        val extraHeaders = HashMap<String, String>()
                        extraHeaders["Referer"] = BASEURL
                        view.loadUrl(url, extraHeaders)
                        return true
                    } else {
                        browse(url)
                        return true
                    }
                } catch (e: Exception) {
                    //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return false
                }
            }

            override fun onPageCommitVisible(view: WebView?, url: String?) {
                super.onPageCommitVisible(view, url)
            }

            override fun onPageFinished(view: WebView, url: String) {
                val js =
                    "javascript:(function() {document.getElementById(\"j_page_header\").style.display=\'none\';" + "})()"
                Log.e("TAG", "onPageFinished: " + url)
                if (url.contains("ct=qun&ac=info")) {
                    Log.e("TAG", "shouldOverrideUrlLoading:555 " + url)
                    more.setVisibility(true)
                    refresh.setVisibility(false)
                    more.setOnClickListener {
                        var id = ""
                        showExitQunDialog {
                            kotlin.runCatching {
                                val split = url.split("&")
                                split.forEach {
                                    Log.e("TAG", "shouldOverrideUrlLoading: " + it)
                                    if (it.contains("id=")) {
                                        Log.e("TAG", "shouldOverrideUrlLoading:1111 " + it)
                                        val split = it.split("=")
                                        Log.e("TAG", "shouldOverrideUrlLoading:1111 " + split)
                                        id = split[1]
                                    }
                                }
                            }
                            GameRequest.exitGameQun(id) {
                                finish()
                            }

                        }
                    }
                    view.loadUrl(js)
                } else {
                    view.loadUrl(js)
                }

                super.onPageFinished(view, url)
            }
        }

        val instance = CookieManager.getInstance()
        instance.setAcceptThirdPartyCookies(webview, true)
        webview.loadUrl(link ?: "")
    }

    private var photos: ArrayList<Photo> = arrayListOf()

    private fun openImageChooserActivity() {
        EasyPhotos.createAlbum(this, false, false, GlideEngine)
            .complexSelector(true, 1, 9)
            .setVideo(true)
            .setGif(false)
            .start(object : SelectCallback() {
                override fun onResult(photo: ArrayList<Photo>, isOriginal: Boolean) {
                    photos.clear()
                    photos.addAll(photo)

                    var photo1 = arrayOfNulls<Uri>(photo.size)
                    photo.forEachIndexed { index, photo ->
                        photo1[index] = photo.uri
                    }
                    Log.e("TAG", "onResult: " + photo1.size)
                    Log.e("TAG", "onResult: " + photo1.size)
                    if (mUploadCallbackAboveL != null) {
                        mUploadCallbackAboveL!!.onReceiveValue(photo1)
                        mUploadCallbackAboveL = null
                    }
                }

                override fun onCancel() {

                }
            })


    }

    override fun onBackPressed() {

        if (webview.canGoBack()) {
            webview.goBack()
        } else {
            finish()
        }
    }

    override fun onRestart() {
        super.onRestart()
        if (canClose) finish()
    }
}

fun Activity.jsAlert(
    view: WebView?,
    url: String?,
    message: String?,
    result: JsResult?
): Boolean {
    when {
        message?.startsWith("web图片上传") == true -> {
            val newWords = message.replace("web图片上传", "")
            val count = if (newWords.isEmpty()) 1 else newWords.toInt()
            EasyPhotos.createAlbum(this, false, false, GlideEngine)
                .setCount(count)
                .setGif(false)
                .setVideo(false)
                .start(object : SelectCallback() {
                    override fun onResult(photos: ArrayList<Photo>, isOriginal: Boolean) {
                        val loading = showLoadingDialog("正在上传图片").apply { show() }
                        var count = 0
                        var photo = ""
                        photos.forEach {
                            AppRequest.uploadImage(this@jsAlert, it.uri) {
                                photo += ("${this},")
                                count += 1
                                if (count == photos.size) {
                                    loading.dismiss()
                                    view?.loadUrl("javascript:upload_img('${photo}')")
                                }
                            }
                        }
                    }

                    override fun onCancel() {}
                })

            result?.cancel()
            return true
        }

        message == "注销成功" -> {
            message?.toast()
            MMKVConsts.uid = ""
            startActivity(intentFor<MainActivity>().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
            result?.cancel()
            return true
        }
        message == getString(R.string.winningRecord) -> {
            result?.cancel()
            startActivity<ZJLSActivity>()
            return true
        }
        message?.startsWith("gid") ?: false -> {
            result?.cancel()
            startGameDetailActivity(message?.substring(4))
            return true
        }
        message?.startsWith("shequ_id") ?: false -> {
            result?.cancel()
            message?.substring(9)?.let { CommunityActivity.start(this, it) }
            return true
        }
        message == "tuijianqunliao" -> {
            result?.cancel()
            GroupChatActivity.start(this)
            return true

        }
        else -> {
            message?.toast()
            result?.cancel()
            return true
        }
    }
    result?.cancel()
    return true
}